package com.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.Demo;
import com.pojo.DemoSaveDto;
import com.pojo.Page;

@Controller
@RequestMapping("/")
public class TestController {

	@GetMapping("j/index")
	public String jIndex(Model model) {
		System.out.println("jsp index");
		model.addAttribute("msg", "hello jsp:" + LocalDateTime.now());
		return "jsp/index";
	}

	@RequestMapping("j/list")
	public String jList(Model model, Map<String, Object> ps, Page<Demo> page) {
		System.out.println(ps);
		if (null == page) {
			page = new Page<>(1, 2);
		}
		List<Demo> list = getList("jsp");
		page.setCount(list.size());
		page.setList(list);
		model.addAttribute("page", page);
		return "jsp/index";
	}

	// thymeleaf
	@GetMapping("t/index")
	public String tIndex(Model model) {
		System.out.println("t index");
		model.addAttribute("msg", "hello thymeleaf:" + LocalDateTime.now());
		return "thymeleaf/index";
	}

	@GetMapping("t/list")
	public String tList(Model model) {
		model.addAttribute("list", getList("thymeleaf"));
		return "thymeleaf/index";
	}

	// freemarker
	@GetMapping("f/index")
	public String fIndex(Model model) {
		System.out.println("f index");
		model.addAttribute("msg", "hello freemarker:" + LocalDateTime.now());
		return "freemarker/index";
	}

	@GetMapping("f/list")
	public String fList(Model model) {
		model.addAttribute("list", getList("freemarker"));
		return "freemarker/index";
	}

	private List<Demo> getList(String name) {
		return IntStream.range(1, 20).mapToObj(i -> new Demo(i + "", name + "_name_" + i)).toList();
	}

	@PostMapping("save/demo")
	@ResponseBody
	public Map<String, Object> saveDemo(@RequestBody Demo d) {
		System.out.println(d);
		return Map.of("success", true);
	}

	@PostMapping("demo/deleteByIds")
	@ResponseBody
//	public Map<String, Object> saveDemo(@RequestBody String[] ids) {
	public Map<String, Object> saveDemo(@RequestBody List<String> ids) {
		System.out.println(ids);
		return Map.of("success", true);
	}

	@PostMapping("demo/saveBatch")
	@ResponseBody
	public Map<String, Object> saveBatch(@RequestBody List<Demo> list) {
		System.out.println(list);
		return Map.of("success", true);
	}

	@PostMapping("demo/saveDto")
	@ResponseBody
	public Map<String, Object> save1(@RequestBody DemoSaveDto vo) {
		System.out.println(vo);
		return Map.of("success", true);
	}

	@PostMapping("getWechatInfo")
	@ResponseBody
	public Map<String, Object> getWechatInfo(@RequestBody Map<String, Object> ps) throws IOException {
		System.out.println(ps); // {code=051daDkl2XK2I94hHHkl2pGHCq1daDkM}
		// 1. 获取code
		String code = (String) ps.get("code");
		// 2. 请求微信接口换取 openId, sessionKey, unionId
		// 接口文档参考https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

		/**
		 * 请求数据示例 GET
		 * https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
		 * 
		 * 返回数据示例 { "openid":"xxxxxx", "session_key":"xxxxx", "unionid":"xxxxx",
		 * "errcode":0, "errmsg":"xxxxx" }
		 */

		String appID = "wxbb5ae21sdfsdf";//注意测试小程序的时候 小程序appID要和这里一制
		String appSecret = "cdb0f1c9481998173dasfasfa5";
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
		
		URL client = new URL(String.format(url, appID, appSecret, code));
		BufferedReader br = new BufferedReader(new InputStreamReader(client.openStream(), "UTF-8"));
		String json = br.lines().collect(Collectors.joining());
		System.out.println(json);
		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> resMap = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
		});
		// 3. 用返回的openId 或 unionId从本地数据库查询 用户是否已经绑定本地账号
		//这里需要自定义操作，根据自己的账号系统做具体处理
		String openid = resMap.get("openid");
		String unionid = resMap.getOrDefault("unionid","");
		// 4. 如果已经绑定本地账号则直接发放token ,否则不生成token
		// token规则需要自定义
		String token = String.valueOf(System.currentTimeMillis());

		return Map.of("success", true, "token", token,"openid",openid,"unionid",unionid);
	}

}